<template>
  <div>
    <el-container>
      <el-header>
        <div class="header-container">
          <h1>用户管理系统</h1>
          <div class="search-box">
            <el-input
              v-model="searchQuery"
              placeholder="请输入用户名或邮箱查询"
              clearable
              @clear="resetSearch"
              @keyup.enter.native="handleSearch"
              style="width: 250px; margin-right: 10px"
            ></el-input>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-main>
          <el-table :data="displayData" stripe style="width: 100%">
            <el-table-column
              prop="name"
              label="用户名"
              :width="tableWidth / 3"
            ></el-table-column>
            <el-table-column
              prop="email"
              label="邮箱"
              :width="tableWidth / 3"
            ></el-table-column>
            <el-table-column label="操作" :width="tableWidth / 3">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editUser(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteUser(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <el-button type="danger" @click="deleteAllUsers"
            >删除全部用户</el-button
          >
          <el-button type="primary" @click="showAddUserDialog"
            >添加用户</el-button
          >
        </el-footer>
      </el-container>
    </el-container>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="用户信息">
      <el-form :model="formData" ref="formRef" label-width="100px">
        <el-form-item
          label="用户名"
          prop="name"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ]"
        >
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
          :rules="[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
              type: 'email',
              message: '请输入正确的邮箱格式',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="formData.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>

    <!-- 空状态提示 -->
    <div v-if="tableData.length === 0" class="empty-state">
      <el-empty description="暂无用户数据"></el-empty>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      tableData: [],
      displayData: [],
      dialogVisible: false,
      formData: { name: "", email: "" },
      currentUserId: null,
      tableWidth: 0,
      searchQuery: "",
    };
  },
  mounted() {
    console.log("Component mounted");
    this.getUsers(); // 调用获取用户列表的方法
    this.updateTableWidth();
    window.addEventListener("resize", this.updateTableWidth);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.updateTableWidth);
  },
  computed: {
    hasSearchResults() {
      return this.searchQuery && this.displayData.length === 0;
    },
  },
  methods: {
    updateTableWidth() {
      const tableContainer = this.$el.querySelector(".el-table");
      if (tableContainer) {
        this.tableWidth = tableContainer.offsetWidth;
      }
    },
    handleSearch() {
      const query = this.searchQuery.trim().toLowerCase();

      if (!query) {
        this.displayData = [...this.tableData];
        return;
      }

      this.displayData = this.tableData.filter(
        (user) =>
          user.name.toLowerCase().includes(query) ||
          user.email.toLowerCase().includes(query)
      );
    },
    resetSearch() {
      this.searchQuery = "";
      this.displayData = [...this.tableData];
    },
    showAddUserDialog() {
      this.currentUserId = null;
      this.formData = { name: "", email: "" };
      this.$refs.formRef && this.$refs.formRef.resetFields();
      this.dialogVisible = true;
    },
    editUser(row) {
      this.currentUserId = row.id;
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    deleteUser(row) {
      this.$confirm("确定要删除该用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete(`/api/users/${row.id}`)
            .then(() => {
              const index = this.tableData.findIndex(
                (item) => item.id === row.id
              );
              if (index !== -1) {
                this.tableData.splice(index, 1);
                this.handleSearch();
                this.$message({ type: "success", message: "删除成功" });
              }
            })
            .catch((error) => {
              console.error("删除用户失败:", error);
            });
        })
        .catch(() => {});
    },
    deleteAllUsers() {
      this.$confirm("确定要删除全部用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete("/api/users")
            .then(() => {
              this.tableData = [];
              this.displayData = [];
              this.$message({ type: "success", message: "已删除全部用户" });
            })
            .catch((error) => {
              console.error("删除全部用户失败:", error);
            });
        })
        .catch(() => {});
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.currentUserId !== null) {
            axios
              .put(`/api/users/${this.currentUserId}`, this.formData)
              .then(() => {
                this.getUsers();
                this.dialogVisible = false;
                this.$message({ type: "success", message: "更新成功" });
              })
              .catch((error) => {
                console.error("更新用户失败:", error);
              });
          } else {
            axios
              .post("/api/users", this.formData)
              .then(() => {
                this.getUsers();
                this.dialogVisible = false;
                this.$message({ type: "success", message: "添加成功" });
              })
              .catch((error) => {
                console.error("添加用户失败:", error);
              });
          }
        }
      });
    },
    getUsers() {
      axios
        .get("/api/users/get") // 修改请求路径
        .then((response) => {
          this.tableData = response.data;
          this.displayData = response.data;
        })
        .catch((error) => {
          console.error("获取用户列表失败:", error);
        });
    },
  },
};
</script>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.search-box {
  display: flex;
  align-items: center;
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}
</style>
